<template>
  <div class="app-container">
    <el-row type="flex" justify="center" align="middle">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header">
            <div class="title-box" style="padding-top: 10px; padding-bottom: 13px;">
              <span>接口管理</span>
            </div>
          </div>
          <el-input v-model="filterOrgText" v-perm="['api-search']" class="mgb-15" :placeholder="filterPlaceholderText" />
          <div style="margin-bottom: 10px;" />
          <el-tree
            ref="apiTreeRef"
            v-loading="viewLoading"
            :filter-node-method="filterNode"
            :data="ApiTreeData"
            :props="treeProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>
                <span v-if="data.level===0" class="mgl-10"><span class="menu-title">{{ data.name }}</span><span style="margin: 5px" /><el-tag class="mgl-10" type="success" size="mini">全部</el-tag></span>
                <span v-if="data.level===1" class="mgl-10"><span class="menu-title">{{ data.name }}</span><span style="margin: 5px" /><el-tag class="mgl-10" type="success" size="mini">模块</el-tag></span>
                <span v-else-if="data.level===2" class="mgl-10"><span class="item-title">{{ data.name }}</span><span style="margin: 5px" /><el-tag class="mgl-10" type="warning" size="mini">接口</el-tag></span>
                <span v-else-if="data.level===3" class="mgl-10"><span class="button-title">{{ data.name }}</span><span style="margin: 5px" /><el-tag class="mgl-10" type="danger" size="mini">按钮</el-tag></span>
              </span>
              <span>
                <el-tooltip v-if="data.level<2" v-perm="['api-insert']" :content="buttonName(buttonType.ADD,data.level)" placement="top">
                  <el-button type="text" size="mini" icon="el-icon-plus" @click="handleAddButton(data)" />
                </el-tooltip>
                <el-tooltip v-if="data.level>0" v-perm="['api-update']" :content="buttonName(buttonType.UPDATE,data.level)" placement="top">
                  <el-button type="text" size="mini" icon="el-icon-edit" @click="handleUpdateButton(data)" />
                </el-tooltip>
                <el-tooltip v-if="data.level>0" v-perm="['api-delete']" :content="buttonName(buttonType.DELETE,data.level)" placement="top">
                  <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDeleleButton(data)" />
                </el-tooltip>
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
    </el-row>
    <!--弹窗：新增或编辑权限-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="80%" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="temp" label-position="top" :rules="rules">
        <el-form-item v-if="dialogStatus=='updateButton'" label="ID">
          <el-input v-model="temp.id" disabled />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="父级节点">
          <el-input v-model="temp.parent_name" :disabled="true" />
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="temp.level_name" :disabled="true" />
        </el-form-item>
        <el-form-item v-if="temp.level>1" label="API地址" prop="url">
          <el-input v-model="temp.url" />
        </el-form-item>
        <el-form-item label="顺序" prop="sort">
          <el-input v-model="temp.sort" type="number" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.description" type="textarea" placeholder="请输入描述或备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='addButton'" type="primary" @click="addButton">确定</el-button>
        <el-button v-if="dialogStatus=='updateButton'" type="primary" @click="updateButton">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import repApi from '@/api/api'
import { root, confirm, tenantType, buttonType } from '@/utils/constants'
import { parseTime, resetTemp } from '@/utils'
import debounce from 'lodash/debounce'

export default {

  name: 'ApiManage',
  data() {
    return {
      rules: {
        name: [{ required: true, message: '必填', trigger: 'blur' }],
        url: [{ required: true, message: '必填', trigger: 'blur' }],
        sort: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      viewLoading: false,
      tableQuery: {
        nick: null
      },
      tenantType,
      buttonType,
      filterPlaceholderText: '输入接口名称过滤',
      filterOrgText: '',
      ApiTreeData: [],
      treeProps: {
        label: 'label',
        children: 'children'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        idx: null,
        id: null,
        name: null,
        title: null,
        description: null,
        parent_id: null,
        parent_name: null,
        parent: null,
        level: null,
        level_name: null,
        url: null,
        sort: null
      },
      textMap: {
        addButton: '添加接口',
        updateButton: '更新接口',
        deleteButton: '删除接口'
      }
    }
  },

  created() {
    this.fetchData()
  },

  watch: {
    'filterOrgText': debounce(function(val) {
      this.$refs.apiTreeRef.filter(val)
    }, 600)
  },

  methods: {
    // 查询
    fetchData() {
      this.viewLoading = true
      repApi.apiTree().then(res => {
        this.ApiTreeData = res.data
        this.viewLoading = false
      }).catch(err => {
        this.ApiTreeData = []
        this.viewLoading = false
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    /**
       * 添加接口
       */
    handleAddButton(data) {
      this.dialogStatus = 'addButton'
      resetTemp(this.temp)
      this.temp.parent = data
      this.temp.parent_name = data.name
      this.temp.parent_id = data.id
      this.temp.level_name = this.buttonName(buttonType.ADD, data.level, true)
      this.temp.level = this.buttonLevel(buttonType.ADD, data.level)
      this.textMap[this.dialogStatus] = this.dialogTitle(buttonType.ADD, data.level)
      this.temp.sort = 10
      this.dialogFormVisible = true
      this.$nextTick(() => this.$refs['dataForm'].clearValidate())
    },
    addButton() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        const data = Object.assign({}, this.temp)// copy obj
        repApi.apiStore(data).then((res) => {
          this.dialogFormVisible = false
          this.fetchData()
          this.$message.success('添加接口成功')
        })
      })
    },
    findApi(childs, pid) {
      if (!childs.length) { return null }
      for (const org of childs) {
        if (org.id === pid) { return org }
        if (org.children) {
          const corg = this.findApi(org.children, pid)
          if (corg) { return corg }
        }
      }
      return this.ApiTreeData[0]
    },

    /**
       * 更新按钮权限
       */
    handleUpdateButton(data) {
      this.dialogStatus = 'updateButton'
      this.temp = Object.assign({}, data) // copy obj
      const parent = this.findApi(this.ApiTreeData[0].children, this.temp.parent_id)
      this.temp.parent = parent
      this.temp.parent_name = parent.name
      this.temp.level_name = this.buttonName(buttonType.UPDATE, data.level, true)
      this.temp.level = this.buttonLevel(buttonType.UPDATE, data.level)
      this.textMap[this.dialogStatus] = this.dialogTitle(buttonType.UPDATE, data.level)
      this.dialogFormVisible = true
      this.$nextTick(() => this.$refs['dataForm'].clearValidate())
    },
    updateButton() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        const data = Object.assign({}, this.temp)// copy obj
        repApi.apiStore(data).then(res => {
          this.dialogFormVisible = false
          this.fetchData()
          this.$message.success('更新接口成功')
        })
      })
    },
    tenantChange(val) {
      console.log(val)
      this.$store.dispatch('ActiveTenement', val).then(res => {
        resetTemp(this.tablePage)
        this.fetchData()
      })
    },

    /**
       * 删除按钮权限
       */
    handleDeleleButton(data) {
      this.dialogStatus = 'deleteButton'
      const delOrg = this.dialogTitle(buttonType.DELETE, data.level)
      this.$confirm(`您确定要永久删除该${delOrg}？`, '提示', confirm).then(() => {
        repApi.apiDelete(data.id).then(() => {
          this.fetchData()
          this.$message.success(`删除${delOrg}成功`)
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    buttonName(typeName, level, single = false) {
      if (typeName === buttonType.ADD || !typeName) {
        if (level == 0) {
          return !single ? typeName + '模块' : '模块'
        }
        return !single ? typeName + '接口' : '接口'
      } else {
        if (level == 1) {
          return !single ? typeName + '模块' : '模块'
        }
        return !single ? typeName + '接口' : '接口'
      }
    },
    buttonLevel(typeName, level) {
      if (typeName === buttonType.ADD) {
        if (level == 0) {
          return 1
        }
        return 2
      } else {
        if (level == 1) {
          return 1
        }
        return 2
      }
    },
    dialogTitle(typeName, level) {
      if (typeName === buttonType.ADD) {
        if (level == 0) {
          return '添加模块'
        }
        return '添加接口'
      } else if (typeName === buttonType.UPDATE) {
        if (level == 1) {
          return '更新模块'
        }
        return '更新接口'
      } else {
        if (level == 1) {
          return '模块'
        }
        return '接口'
      }
    }

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import 'src/styles/variables.scss';
  .mgl-10 {
      margin-left: 10px;
    }
  .menu-title{
    font-weight: bold;
    color: $top-color;
  }
  .item-title{
    font-weight: normal;
    color:$tenant-color;
  }
  .button-title{
    font-weight: lighter;
    color: $company-color;
    font-size: small;
  }
  .title-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    span {
      font-size: 22px;
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .mgb-15 {
    margin-bottom: 15px;
  }
</style>
